<?php
namespace frontend\controllers;

use frontend\models\ResendVerificationEmailForm;
use frontend\models\VerifyEmailForm;
use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use common\models\Users;
use common\models\Orders;

/**
 * Site controller
 */
class IndexController extends Controller
{

    //响应
    public function actionResponse(){
        $res=\Yii::$app->response;
        //设置状态头
        $res->statusCode=200;
        //设置响应头
        $a=$res->headers->set('aa',456);
        $a=$res->headers->set('pragma','no-ca');
        p($a);
    }

    //请求
    public function actionRequest(){
        $res = \Yii::$app->request;
        //默认值 0，如果不设置默认值为null
        $id = $res->get('id',0);
        p($id);
        $name = $res->post('name');
        p($name);
        p($res->isPost);
        p($res->isGet);
        p($res->isAjax);
        p($res->isPut);
        //获取请求头
        $a=$res->getHeaders()->toArray();
        p($a);
    }


    //管理模型查询
    public function actionUser(){
        $id_ar=[41567,31391];
        $user = Users::find()->where(['id'=>$id_ar])->with('orders')->asArray()->all();
        p($user);die;
    }

    //关联模型查询1
    public function actionUser1(){
        $id=31391;
        $user= Users::find()->where(['id'=>$id])->one();

        //对象数据转换数组
        p($user->getAttributes());
        //通过对象访问
        p($user->name);
        //通过对象访问
        p($user->getAttribute('name'));
        $orders = $user->orders;
        //$orders = $user->getOrders();
        p($orders);die;
    }


    public function actionModel(){
        //初始化数据模型，选定场景，不选择默认场景是default
        $user= new Users(['scenario'=>'login']);

        //$user->scenarios='default' 来切换模型场景
        //模型验证场景名称 调用一个不存在的
        //熟悉，通过魔术方法__set()调用了getScenario()方法
        p($user->scenario);
        //模型场景名称
        p($user->getScenario());
        //获取所有的模型的场景
        $a= $user->scenarios();
        p($a);


        $user->bankCard=5;
        //验证模型规则
        if($user->validate()){
            p('验证通过');
        }else{ //验证不通过会把错误信息存在errors属性里。
            p($user->errors);
        }

        die;
    }

    //模型1
    public function actionModel1(){
        //实例化Users模型 空的数据模型
        $user= new Users();
        //返回活动记录对象 yii\db\ActiveRecord对象 可以用于操作模型，查询，添加，修改，删除
        $query=$user::find()->where(['id'=>1]);
//        p($query);

        //返回查询后的数据模型 ，模型中已经有数据
        $user_data=$query->one();
//        p($query->count());
//        p($data);die;

        //获取数据库连接对象 yii\db\Connection
        $connection_ob = $user::getDb();
//      p($connection_ob);

        $id_ar=[41567,31391];
//        $user->where(['id'=>$id_ar]);
        //获取数据表结构，包含表名，主键，字段信息
        p($user_data::getTableSchema());
        //获取表的所有的字段
        p($user_data->attributes());

        //获取表的主键
        p($user_data->getAttributes());

        die;
    }

    //原生查询
    public function actionModel2(){
        //实例化Users模型
        $user= new Users();
        $id=1;
        $sql="select * from user where id=:id ";

        //返回活动记录对象。半原生sql查询
        $query=$user::findBySql($sql,[':id'=>$id]);
        //返回模型对象，已经有数据填充
        $data = $query->asArray()->one();
        p($data);
        //返回活动记录要执行的sql
        p($query->sql);
    }

    public function actionModel3(){
        $user= new Users();
        //用模型直接查询的方法
        $id=1;
        //直接查询单条
        $data=$user::findOne(['id'=>$id]);
        //可以直接用主键查询
        $data=$user::findOne($id);
        p($data->getAttribute('id')); //获取查询数据中字段值
        p($data->getAttributes()); //获取所有字段值
        p($data->attributes); //获取所有字段值  调用一个不存在的属性，变相的调用了getAttributes()方法

        //查询多条
        $data = $user::findAll(['id'=>[1,6]]);
        $data = $user::findAll($id);
        p($data); //二位数组，每个元素都是一个模型对象
        //findOne,findAll只能返回数据表的模型对象，不能直接返回数组
        die;
    }

    //查询。
    public function actionModel4(){
        $user= new Users();
        //返回数据库的命令对象，yii\db\Command Object
        $data=$user::find()->where("id=:id")->createCommand()->bindValue(":id",1)->queryOne();
        p($data);
//        $ob->getRawSql(); //获取待执行的sql

        $id=1;
        $id_ar=[1,2];
        $name='abc';
        $phone='13253602577';
        $idCard='';

        //多个where()后面的where()会覆盖前面的where(),可以使用andWhere(),或者orWhere()
        //where()，filterWhere()会覆盖前面所有的查询。相当于初始化了查询。
        //where(),filterWhere()一定要放在第一个位置。
        $query=$user->find()->where(['id'=>$id])
            ->andWhere(['id'=>$id_ar]) //hash  id对应一个数组，自动生成 id in ()
            ->andWhere("id=:id",[':id'=>$id])//字符串，可以帮到变量
            ->andWhere(['=','phone',$phone]) //操作符形式
            ->andWhere(['like','name',$name])
            ->andWhere(['not between','id',2,9])
            ->andWhere(['or',['like','name',$name],['like','phone',$name]])
            ->orWhere(['>','id',$id])
            ->andFilterWhere(['idCard'=>$idCard]) //如果$idCard为空不会参与查询。filterWhere(),orFilterWhere()一样。
            ->orderBy('id desc,phone asc')
            ->orderBy(['id'=>'asc','phone'=>'desc'])
            ->groupBy('id');
          $sql=$query->createCommand()->getRawSql();
//          $one_data= $query->one(); //取一条数据
//          $all_data= $query->all(); //取出所有数据
//          $column_data= $query->column(); //返回结果集第一列
//          $count= $query->coount(); //返回结果集第一列

//        p($user);die;

        // indexBy()返回的二维数组以某个字段当key
        $data= $user->find()->limit(2)->asArray()->indexBy('id')->all();
        p($data);
        p($sql);

        //如果要查询非常条数据，可以用下面的方法，每次查询一定数量的数据释放内存后再循环查询。
        $data=[];
        foreach($user->find()->limit(10)->asArray()->select(['id','name','phone'])->batch(4) as $ob){
            $data=array_merge($data,$ob);
        }
        p($data);
        die;
    }

    public function actionModel5(){
        $user= new Users();
        $user->name='123';
        $user->phone='13253602576';
        if(!$user->validate() && $user->errors){
            //验证不通过返回错误信息
            p(current($user->errors)[0]);
            die;
        }
//        if($user->save()){
//            p('添加成功');
//        }

        if($user->insert()){
            p('添加成功1');
        };

        //$user->update()  更新
        //新添加数据的主键id值
        p($user->getPrimaryKey());die;
    }

    public function actionModel6(){
        $user = new Users();
        $user->name='123';
        $user->phone='13253602565';
        //插入数据
        $user->save();

        $user= Users::findOne(1);
        $user->name='123';
        $user->phone='13253602565';
        //更新数据
        $user->save();
        //当调用save()的时候，会自动验证 validate()。

        //更新计数
        $post = Users::findOne(100);
        // UPDATE `post` SET `view_count` = `view_count` + 1 WHERE `id` = 100
        $post->updateCounters(['num_number' => 1]);

        //默认属性值
        $user= new Users();
        $user->loadDefaultValues();

        //更新多行数据
        Users::updateAll(['phone'=>'123'],['id'=>[1,6,8]]);

        //删除数据
        $user = Users::findOne(1);
        $user->detete();

        //删除多条数据
        Users::deleteAll(['id'=>[1,2,3]]);


    }



    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'my_behavior'=>[
                'class'=>\common\component\MyBehavior::class,
                'property'=>'22',
<<<<<<< HEAD
                'only'=>['index',''],
            ]
=======
            ],
            'my_filter'=>[
                'class'=>\common\component\MyFilter::class,
            ],
>>>>>>> aad7d06a35a780ce80b37846aa7d2a35aa737500
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
            'abc'=>[
                'class'=>'common\component\TestAction',
                'name'=>'旅游'
            ],


        ];
    }




    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {

        echo 55;
       // return $this->render('index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            Yii::$app->session->setFlash('success', 'Thank you for registration. Please check your inbox for verification email.');
            return $this->goHome();
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    /**
     * Verify email address
     *
     * @param string $token
     * @throws BadRequestHttpException
     * @return yii\web\Response
     */
    public function actionVerifyEmail($token)
    {
        try {
            $model = new VerifyEmailForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($user = $model->verifyEmail()) {
            if (Yii::$app->user->login($user)) {
                Yii::$app->session->setFlash('success', 'Your email has been confirmed!');
                return $this->goHome();
            }
        }

        Yii::$app->session->setFlash('error', 'Sorry, we are unable to verify your account with provided token.');
        return $this->goHome();
    }

    /**
     * Resend verification email
     *
     * @return mixed
     */
    public function actionResendVerificationEmail()
    {
        $model = new ResendVerificationEmailForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
                return $this->goHome();
            }
            Yii::$app->session->setFlash('error', 'Sorry, we are unable to resend verification email for the provided email address.');
        }

        return $this->render('resendVerificationEmail', [
            'model' => $model
        ]);
    }
}
